<template lang="pug">
  el-upload(
    ref="uploadFile"
    :class="!avatarFlag ? '' : 'avatar-uploader'"
    :list-type="listType"
    :action="action ? BASE_URL + action : ''"
    :file-list="fileList"
    :on-change="fileChange"
    :on-exceed="exceedHandle"
    :before-upload="beforeUpload"
    :on-success="onSuccess"
    :on-preview="onPreview"
    :on-remove="onRemove"
    v-bind="$attrs"
    with-credentials
  )
    slot
      el-button(:size="btnSize" type="primary" v-if="!avatarFlag")
        i(class="mr5 f16" v-if="!noIcon" :class="icon ? icon : 'el-icon-upload'")
        | {{btnText}}
      span.ml5.f12.c_secondary(v-if="suffix") {{suffix}}
      el-image(
        :src="imageUrl"
        class="avatar"
        v-if="avatarFlag && fileList.length > 0"
        fit="fill"
        )
      i(v-if="avatarFlag && fileList.length === 0" class="el-icon-plus avatar-uploader-icon")
</template>
<script>
export default {
  name: 'UploadFile',
  props: {
    listType: {
      type: String,
      default: 'text'
    },
    action: {
      type: String,
      default: ''
    },
    icon: {
      type: String,
      default: ''
    },
    // 注脚
    suffix: {
      type: String,
      default: ''
    },
    avatarFlag: {
      type: Boolean,
      default: false
    },
    noIcon: {
      type: Boolean,
      default: false
    },
    // 初始话已上传文件,对外暴露value属性，用于显示隐藏弹框
    filedList: {
      type: Array,
      default: () => []
    },
    // 限制文件上传大小
    limitSize: {
      type: Number,
      default: 0
    },
    btnSize: {
      type: String,
      default: 'small'
    },
    btnText: {
      type: String,
      default: '点击上传'
    },
    changeHandle: {
      type: Function,
      default: null
    },
    rest: {
      type: Object,
      default: () => {}
    },
    success: {
      type: Function,
      default: null
    },
    remove: {
      type: Function,
      default: null
    },
    progress: {
      type: Function,
      default: null
    },
    change: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      // fileList: [...this.filedList]
    }
  },
  computed: {
    fileList: {
      get () {
        this.filedList.map((x) => {
          if (
            x.url &&
            (x.url.startsWith('http') ||
              x.url.startsWith(this.BASE_URL) ||
              x.url.startsWith('blob:'))
          ) {
            return x
          }
          x.url = this.BASE_URL + x.url
          return x
        })
        return [...this.filedList]
      },
      set (val) {
        console.log(val)
        this.$emit('update:filedList', val)
      }
    },
    imageUrl () {
      if (!this.avatarFlag) {
        return ''
      }
      const fileObj =
        this.fileList.length > 0 ? this.fileList[this.fileList.length - 1] : {}
      let url = ''
      if (fileObj.url) {
        url = fileObj.url
      }
      if (
        fileObj.response &&
        fileObj.response.fileList &&
        fileObj.response.fileList[0]
      ) {
        url = fileObj.response.fileList[0].filePath
      }
      if (!url) {
        return ''
      } else {
        console.log(this.UPLOAD_UTL, url)
        return url.startsWith('http')
          ? url
          : url.startsWith(this.BASE_URL)
            ? url
            : this.BASE_URL + url
      }
    }
  },
  methods: {
    fileChange (file, fileList) {
      console.log(fileList)
      this.fileList = fileList
      this.$emit('change', fileList)
    },
    onSuccess (response, file, fileList) {
      this.fileList = fileList
      if (this.success) {
        this.success({ response, file, fileList })
      }
      this.$emit('success', fileList)
    },
    onRemove (file, fileList) {
      this.fileList = fileList
      if (this.remove) {
        this.remove({ file, fileList })
      }
      this.$emit('remove', file)
    },
    exceedHandle () {
      this.$message.error('文件超出个数限制')
    },
    onPreview (e) {
      if (e?.type !== 'video') return
      if (e?.url) {
        window.open(e.url)
      }
    },
    beforeUpload (file) {
      const { limitSize, limit, action, rest } = this.$props
      const { fileList } = this
      return new Promise((resolve, reject) => {
        const total = fileList.length + 1

        for (let i = 0; i < fileList.length; i++) {
          if (
            fileList[i].originFileObj &&
            fileList[i].originFileObj.name === file.name &&
            fileList[i].originFileObj.size === file.size
          ) {
            this.$message.error('请不要上传重复附件', 2)
            reject(new Error())
          }
        }

        // 判断上传个数
        if (limit && total > limit) {
          this.$message.error('最多只能上传' + limit + '张', 2)
          reject(new Error())
          return
        }

        // 判断上传文件大小
        if (limitSize && file.size / 1024 / 1024 > limitSize) {
          this.$message.error('文件大小不能超过 ' + limitSize + 'MB!')
          reject(new Error())
          return
        }

        // 判断是否执行上传拦截
        if (!action) {
          // // 根据后台需求数据格式
          // const form = new FormData()
          // // 文件对象
          // form.append(name, file)
          // 项目封装的请求方法，下面做简单介绍
          this.$emit('uploadFile', file, rest)
          reject(new Error())
          return
        }

        resolve()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader .el-upload:hover {
  // border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
